# coding: utf-8

from django.http import HttpResponse
from django.shortcuts import render
import hashlib
from BeautifulSoup import BeautifulSoup
from django.views.decorators.csrf import csrf_exempt


class WeiXin:
    token = "wechat"

    def __init__(self):
        pass

    @staticmethod
    def confirm_weixin(token, timestamp, nonce, signature):
        return hashlib.sha1("".join(sorted([token, timestamp, nonce]))).hexdigest() == signature

    @staticmethod
    def make_text(from_username, to_username, msg, create_time, msg_id):
        template = open("templates/text.xml").read()
        return template % (to_username, from_username, create_time, "text", msg, msg_id)

@csrf_exempt
def main(request):
    if request.method == "GET":
        if WeiXin.confirm_weixin(
                WeiXin.token, request.GET.get("timestamp", ""), request.GET.get("nonce", ""),
                request.GET.get("signature", "")
        ):

            return HttpResponse(request.GET.get("echostr", ""))
    elif request.method == "POST":
        if WeiXin.confirm_weixin(
                WeiXin.token, request.GET.get("timestamp", ""), request.GET.get("nonce", ""),
                request.GET.get("signature", "")
        ):
            print request.body
            return HttpResponse("123")


def test(request):
    return render(request, "html/hello.html", {"name": request.GET.get("name")})
